package com.chain.qs.common.schedule;

import com.chain.qs.modules.biz.dp.handler.AbstractDPHandler;
import com.chain.qs.modules.biz.service.EquSwitcherService;
import com.chain.qs.modules.biz.service.HandoverService;
import com.chain.qs.modules.biz.service.HandoverTaskService;
import com.chain.qs.modules.biz.service.JobOperationService;
import org.quartz.SchedulerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Service
@Lazy(false)
public class StartJobs {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private HandoverService handoverService;

    @Resource
    private EquSwitcherService equSwitcherService;

    @Resource
    private HandoverTaskService handoverTaskService;

    @Resource
    private JobOperationService switcherTaskService;

    private Map<String, AbstractDPHandler> handlerMap = AbstractDPHandler.dpHandlerMap;



    @PostConstruct
    public void initTask() throws SchedulerException {
        logger.info("初始化加载定时任务......");

        //启动值班定时任务
        startHandoverJobs();

        //定时开关机任务
        startSwitcherJobs();

        //数据处理启动方法(默认半小时一次)
        startDp();
    }

    //交接班
    private void startHandoverJobs() throws SchedulerException {
        ArrayList<QuartzJobBean> handoverList = handoverService.getQuartzJobBeanList4ActivedHandover();
        for (QuartzJobBean cur : handoverList) {
            handoverTaskService.initJob(cur);
        }
    }

    //定时开关机
    private void startSwitcherJobs() throws SchedulerException {
        ArrayList<QuartzJobBean> switcherList = equSwitcherService.getQuartzJobBeanList();
        for (QuartzJobBean cur : switcherList) {
            switcherTaskService.initJob(cur);
        }
    }

    //设备历史记录入库
    private void startDp() throws SchedulerException {
        ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                try {
                    for (Map.Entry<String, AbstractDPHandler> entry : handlerMap.entrySet()) {
                        AbstractDPHandler handler = entry.getValue();
                        handler.fixedTimeSaveDataToDB();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        service.scheduleAtFixedRate(runnable, 1, 30, TimeUnit.MINUTES);
    }

}
